﻿package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.external.ExternalInterface;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.net.sendToURL;
	/**
	 * ...
	 * @author www0z0k
	 */
	public class Main extends Sprite 
	{
		private var sound:Sound;//sound container
		private var channel:SoundChannel;//object controlling now playing sound
		private var currentPath: String = 'false';//a path to currently playing file, if nothing is playing value is 'false'
		
		public function Main():void{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			if (ExternalInterface.available) {//registering a function to make it available from javascript
				ExternalInterface.addCallback('playMp3', playMp3);
			}
			trace('check sound');
		}

		private function onEnd(e:Event = null):void {
			try { sound.close(); } catch (er:Error) { }
			try { channel.stop();
			markLink(false);
			currentPath = 'false';
			channel.removeEventListener(Event.SOUND_COMPLETE, onEnd);
			sound.removeEventListener(Event.OPEN, onStart); } catch (err: Error) { };
		}
		
		private function markLink(flag:Boolean):void {
			if(currentPath != 'false'){
				try{
					ExternalInterface.call('highlight', currentPath, flag);//calling 'highlight' function from javascript with 2 arguments
				}catch (er: Error) { }
			}
		}
		
		private function onStart(e:Event):void {
			markLink(true);
			channel = sound.play();
			channel.addEventListener(Event.SOUND_COMPLETE, onEnd);
		}
		
		private function playMp3(path:String = ''):Boolean {
			onEnd(new Event('ololo'));
			if (path == '') {
				return false;
			}
			sound = new Sound();
			sound.addEventListener(Event.OPEN, onStart);
			currentPath = path;
			sound.load(new URLRequest(path));
			return true;
		}			
	}	
}